package com.traffic.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.SocketException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;

import com.traffic.system.model.BusinessException;

import net.sf.json.JSONObject;



/**
 * 
 * @author niegang
 * 
 * @description 发送http请求
 * 
 * @filename HttpUtil.java
 * 
 * @time 2011-6-15 下午05:26:36
 * 
 * @version 1.0
 */

public class HttpUtil {

    public static void main(String[] args) {

       
    }

    public static String post(String url, List<NameValuePair> nvps, String encoding) throws Exception {
        HttpPost httpost = new HttpPost(url);
        String htmlBody = null;
        // 请求超时
        DefaultHttpClient httpclient = new DefaultHttpClient();
        // httpclient.getParams().setParameter(
        // CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
        // // 读取超时
        // httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
        // 5000);
        try {
            //httpost.setHeader("Content-Type", "text/html; charset=" + encoding);
            if (nvps != null) {
                httpost.setEntity(new UrlEncodedFormEntity(nvps, encoding));
            }
            HttpResponse response = httpclient.execute(httpost);
            HttpEntity entity = response.getEntity();
            htmlBody = EntityUtils.toString(entity);
            EntityUtils.consume(entity);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("连接异常！");
        } finally {
            httpost.abort();
            httpclient.getConnectionManager().shutdown();
        }
        return htmlBody;
    }

    public static String postWithStringEntity(String url, Map<String, String> params) throws Exception {
        // return readResponse(url, params, "POST", "utf-8");
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            // httpClient = new SSLClient();
            httpClient = new DefaultHttpClient();
            // 请求超时
            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
            // 读取超时
            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
            httpPost = new HttpPost(url);
            String reqStr = JSONObject.fromObject(params).toString();

            httpPost.setEntity(new StringEntity(reqStr, "utf-8"));

            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "utf-8");
                }
            }
        } catch (Exception ex) {
            LogUtil.getLogger().error("HttpUtil.doPost:" + ex.getMessage());
        }
        return result;
    }

    public static String postWithUrlEncodedFormEntity(String url, Map<String, String> params) throws Exception {
        // return readResponse(url, params, "POST", "utf-8");
        HttpPost httpost = new HttpPost(url);
        String htmlBody = null;
        // 请求超时
        DefaultHttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
        // 读取超时
        httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
        try {
            // httpost.setHeader("Content-Type", "text/html; charset=utf-8");
            if (params != null) {
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                for (String key : params.keySet()) {
                    nvps.add(new BasicNameValuePair(key, params.get(key)));
                }
                httpost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
            }
            HttpResponse response = httpclient.execute(httpost);
            HttpEntity entity = response.getEntity();
            htmlBody = EntityUtils.toString(entity);
            EntityUtils.consume(entity);
        } catch (Exception e) {
            // e.printStackTrace();
            LogUtil.getLogger().error("HttpUtil.doPost2:" + e.getMessage());
            throw new Exception("连接异常！");
        } finally {
            httpost.abort();
            httpclient.getConnectionManager().shutdown();
        }
        return htmlBody;
    }

    /**
     * 执行一个HTTP get请求，返回请求响应的HTML
     * 
     * @param url
     *            请求的URL地址
     * @param params
     *            请求的查询参数,可以为null
     * @return 返回请求响应的HTML
     */
    public static String doGet(String url, Map<String, String> params) {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        // 请求超时
        httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
        // 读取超时
        httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
        HttpGet httpget = new HttpGet();
        String htmlBody = null;
        // 请求超时
        try {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            if (params != null) {
                for (Entry<String, String> e : params.entrySet()) {
                    nvps.add(new BasicNameValuePair(e.getKey(), e.getValue()));
                }
            }
            String str = EntityUtils.toString(new UrlEncodedFormEntity(nvps));
            httpget.setURI(new URI(url + (url.contains("?") ? "&" : "?") + str));
            // httpget.setHeader("User-Agent","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)");
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            htmlBody = EntityUtils.toString(entity);
            EntityUtils.consume(entity);
        } catch (Exception e) {
            // e.printStackTrace();
            LogUtil.getLogger().error("HttpUtil.doGet:" + e.getMessage());
        } finally {
            httpget.abort();
            httpclient.getConnectionManager().shutdown();
        }
        return htmlBody;
    }

    /**
     * 输出内容
     * 
     * @param response
     * 
     * @throws IOException
     */
    public static void outPrint(HttpServletResponse response, String content, String charset) {
        response.setCharacterEncoding(charset);
        response.setContentType("text/html;charset=" + charset);
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.println(content);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.close();
        }
    }

    /**
     * 请求数据并且获得返回值
     * 
     * @param requestUrl
     *            请求链接
     * 
     * @param params
     *            请求参数
     * 
     * @param method
     *            请求方式
     * 
     * @param charset
     *            编码
     * 
     * @return String
     * 
     * @throws IOException
     */
    public static String readResponse(String requestUrl, Map<String, String> params, String method, String charset) {
        StringBuffer sb = new StringBuffer();
        String paramsStr = "";
        if (params != null && params.size() > 0) {
            for (Entry<String, String> e : params.entrySet()) {
                sb.append(e.getKey());
                sb.append("=");
                sb.append(e.getValue());
                sb.append("&");
            }
            paramsStr = sb.substring(0, sb.length() - 1);
        }
        return readResponse(requestUrl, paramsStr, method, charset);
    }

    /**
     * 请求数据并且获得返回值
     * 
     * @param requestUrl
     *            请求链接
     * 
     * @param requestData
     *            请求参数
     * 
     * @param method
     *            请求方式
     * 
     * @param charset
     *            编码
     * 
     * @return String
     * 
     * @throws IOException
     */
    public static String readResponse(String requestUrl, String requestData, String method, String charset) {
        HttpURLConnection conn = null;
        OutputStreamWriter out = null;
        BufferedReader in = null;
        try {
            URL url = new URL(requestUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod(method);
            conn.setRequestProperty("Content-Type", "text/html");
            conn.setRequestProperty("Accept-Charset", charset);
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", "" + requestData.length());
            out = new OutputStreamWriter(conn.getOutputStream(), charset);
            out.write(requestData);
            out.flush();
            out.close();
            // 获取响应状态
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                System.err.println("connect failed!");
                return "";
            } else {
                // 获取响应内容体
                String line, result = "";
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
                while ((line = in.readLine()) != null) {
                    result += line + "\n";
                }
                return result;
            }
        } catch (SocketException se) {
            se.printStackTrace();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

    /**
     * 根据某种编码方式将字节数组转换成字符串
     * 
     * @param b
     *            字节数组
     * @param offset
     *            要转换的起始位置
     * @param len
     *            要转换的长度
     * @param encoding
     *            编码方式
     * @return 如果encoding不支持，返回一个缺省编码的字符串
     */
    public static String getString(byte[] b, int offset, int len, String encoding) {
        try {
            return new String(b, offset, len, encoding);
        } catch (UnsupportedEncodingException e) {
            return new String(b, offset, len);
        }
    }

}
